import {Injectable} from "@angular/core";
import {HEROES} from "./mock-heroes";
import {Hero} from "./Hero";
import {Store} from "./store";

@Injectable()
export class HeroService {
  private id = 21

  constructor(private store: Store) {
  }

  getHeroes() {
    return Promise.resolve(this.store.heroes)
  }

  getHero(id) {
    return this.getHeroes().then(heroes => heroes.find(hero => hero.id === id))
  }

  createHero() {
    let id = this.id++
    let hero = {id: id, name: `Hero ${id}`, editable: true}
    this.store.heroes.push(hero)
  }

  deleteHero(hero: Hero) {
    let idx = this.store.heroes.indexOf(hero)
    this.store.heroes.splice(idx, 1)
  }

  clearHeros() {
    this.store.heroes = null
  }

  resetHeroes() {
    this.store.heroes = [...HEROES]
  }
}